package com.xcf.leetcode;

import java.util.Stack;

/**
 * Formula <br>
 *
 * @author xiaocf <br>
 * @version 1.0 <br>
 * @date 2020/7/29 13:19 <br>
 */
public class Formula {

    public static void main(String[] args) {
        //以空格分隔
        System.out.println(fun("2 + 5 * 3"));
        // 20 + 15 -12 = 23
        System.out.println(fun("2 * 10 + 5 * 3 - 12"));
        // 2 - 75 + 67 = -6
        System.out.println(fun("2 - 5 * 3 * 5 + 67"));
        // 2 - 500 + 67 = -431
        System.out.println(fun("2 - 100 * 5 + 67"));
    }

    private static int fun(String input) {
        String[] items = input.split("\\s");
        Stack<String> stack = new Stack( );
        for (int i = 0; i < items.length; i++) {
            if (!"*".equals(items[i])) {
                stack.push(items[i]);
            } else {
                int res = Integer.valueOf(stack.pop( )) * Integer.valueOf(items[++i]);
                stack.push(String.valueOf(res));
            }
        }
        while (stack.size( ) >= 3) {
            int var1 = Integer.valueOf(stack.pop( ));
            String op = stack.pop( );
            int var2 = Integer.valueOf(stack.pop( ));

            if ("+".equals(op)) {
                stack.push(String.valueOf(var1 + var2));
            } else {
                stack.push(String.valueOf(var2 - var1));
            }
        }
        return Integer.valueOf(stack.pop( ));
    }

    private int cal(String formula) {
        char[] chars = formula.toCharArray( );
        int flag = 0;
        int preNumber = -1;
        int result = 0;
        for (int i = 0; i < chars.length; i++) {
            char currChar = chars[i];
            if (currChar == '+' || currChar == '-' || currChar == '*') {
                // 计算符
                Integer number = Integer.valueOf(formula.substring(flag, i));

            }
        }
        return result;
    }
}
